package br.com.ordersys.framework.i18n;

import java.text.MessageFormat;
import java.util.Locale;
import java.util.ResourceBundle;

import br.com.ordersys.framework.restlayer.RestCallContext;
import br.com.ordersys.framework.restlayer.auth.AuthenticationData;

public class I18n {
	private Class baseClass;

	public I18n(Class baseClass) {
		this.baseClass = baseClass;
	}

	public String get(String key, Object... vs) {
		return get(baseClass, key, vs);
	}

	public String get(String key) {
		return get(baseClass, key, null);
	}

	public static String get(Class baseClass, String key) {
		return get(baseClass, key, null);
	}

	public static String get(Class baseClass, String key, Object... args) {
		AuthenticationData ad = AuthenticationData.get();
		Locale locale = null;

		if (ad == null) {
			RestCallContext restContext = RestCallContext.get();

			if (restContext != null) {
				locale = restContext.getCurrentUserLocale();
			}
		} else {
			locale = ad.getLocale();
		}

		if (locale == null) {
			locale = Locale.getDefault();
		}

		ResourceBundle bundle = ResourceBundle.getBundle(baseClass.getName(), locale, Thread.currentThread().getContextClassLoader());

		String result = bundle.getString(key);

		if (args != null && args.length > 0) {
			result = MessageFormat.format(result, args);
		}

		return result;
	}
}
